<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;
use App\Http\Service\ActivityService;
use App\Http\Service\ConfigService;
use App\Http\Service\GoodsCommentService;
use App\Http\Service\ActivityLogService;
use App\Http\Service\ActivityShareLogService;
use App\Http\Service\PointLogService;
use App\Http\Service\OrderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ActivityController extends BaseController
{

    protected $request;
    protected $user;
    protected $activityService;
    protected $configService;
    protected $goodsCommentService;
    protected $activityLogService;
    protected $activityShareLogService;
    protected $pointLogService;
    protected $orderService;

    public function __construct(Request $request,
                                ActivityService $activityService,
                                ConfigService $configService,
                                GoodsCommentService $goodsCommentService,
                                ActivityLogService $activityLogService,
                                ActivityShareLogService $activityShareLogService,
                                PointLogService $pointLogService,
                                OrderService $orderService)
    {
        $this->request = $request;
        $this->user = $this->request->get('user');
        $this->activityService = $activityService;
        $this->configService = $configService;
        $this->goodsCommentService = $goodsCommentService;
        $this->activityLogService = $activityLogService;
        $this->activityShareLogService = $activityShareLogService;
        $this->pointLogService = $pointLogService;
        $this->orderService = $orderService;
    }

    public function index()
    {
        $appSlider = $this->configService->findFirstRowByFields(['type' => 'activity_slider']);
        $slider = $appSlider['content'];

        $list = $this->activityService->list($this->user, 1);

        return toJSON(['slider' => $slider, 'list' => $list]);
    }

    public function list()
    {
        $page = $this->request->input('page', 1);

        return toJSON($this->activityService->list($this->user, $page));
    }

    public function share()
    {
        $id = $this->request->input('id', 0);

        $activity = $this->activityService->find($id);


        if($activity == null) {
            return toJSON('', \Constant::FAILED, '活动不存在');
        }

        if($activity->need_share == 0) {
            return toJSON('', \Constant::FAILED, '活动不需要分享');
        }

        $shareLog = $this->activityShareLogService->findFirstRowByFields(['user_id' => $this->user->id, 'activity_id' => $id]);

        if($shareLog != null) {
            return toJSON('', \Constant::FAILED, '已分享记录，请勿重复请求');
        }

        // 分享日志记录
        $this->activityShareLogService->create([
            'user_id' => $this->user->id,
            'activity_id' => $id,
        ]);

        return toJSON();
    }

    public function detail()
    {
        $id = $this->request->input('id', 0);
        $activity = $this->activityService->getDetail($this->user, $id);
        // 默认评论
        $activity['default_comments'] = $this->goodsCommentService->getDefault($activity->goods_id);

        // 评论第一页
        $activity['comments'] = $this->goodsCommentService->getList($activity->goods_id, 1);

        // 用户订单
        $activity['order'] = $this->orderService->findFirstRowByFields(['foreign_id' => $id, 'type' => 1, 'user_id' => $this->user->id]);

        return toJSON($activity);
    }

    public function getRobToken()
    {
        $id = $this->request->input('id', 0);

        $activity = $this->activityService->find($id);
        if($activity->need_share == 0) {
            return toJSON('', \Constant::FAILED, '活动不需要分享');
        }

        return toJSON($this->activityService->getRobToken($this->user, $id));
    }

    public function rob()
    {
        $token = $this->request->input('token', '');
        $token = $this->activityService->decryptRobToken($token);

        if ($token == false) {
            return toJSON('', \Constant::FAILED, '数据非法');
        }

        if (time() - $token['timestamp'] > 60) {
            //return toJSON('', \Constant::FAILED, '抢购已结束');
        }

        $activityId = $token['activity_id'];

        $activity = $this->activityService->find($activityId);

        if($activity == null) {
            return toJSON('', \Constant::FAILED, '活动不存在');
        }

        //是否已抢购
        $activityLog = $this->activityLogService->findFirstRowByFields(['user_id' => $this->user->id, 'activity_id' => $activityId]);

        if ($activityLog != null) {
            //return toJSON('', \Constant::NEED_SHOW_MESSAGE, '你已参与本次活动，不能重复参与');
        }

        if ($activity->points > 0 && $this->user->history_points < $activity->points) {
            return toJSON('', \Constant::NEED_SHOW_MESSAGE, '你的积分不够，多多抢购，增加积分噢');
        }

        $currentAt = time();
        if ($activity->end_at < $currentAt) {
            return toJSON('', \Constant::NEED_SHOW_MESSAGE, '抢购结束了，你来晚了，下次准时噢');
        }

        //抢购日志记录
        $activityLog = $this->activityLogService->create([
                'user_id' => $this->user->id,
                'activity_id' => $activityId,
                'is_success'=> 0,
        ]);

        //放这里是为了让抓包提前刷单的，记录日志，下次抢不了
        if ($activity->start_at > $currentAt) {
            return toJSON('', \Constant::NEED_SHOW_MESSAGE, '抢购还未开始，请耐心等待');
        }

        /********** 120客户端积分需要加1 **********/

        //抢购人数
        $this->activityService->update(['in_number' => $activity->in_number + 1], $activity->id);

        $point = 1;
        //用户积分改变
        $this->user->history_points += $point;
        $this->user->points += $point;
        $this->user->save();
        //积分日志
        $this->pointLogService->create([
            'user_id' => $this->user->id,
            'number' => $point,
            'change_desc' => '抢购' . $activity->title,
            'change_type' => 1,
        ]);

        if ($activity->remaining_number == 0) {
            return toJSON('', \Constant::GOODS_NO_STOCK);
        }

        //减轻抢购压力解决方案
//         $microtime = explode(' ', microtime());
//         $singleDigit = (int)substr((int)($microtime[0] * 1000), -1); //个位数
//         if (in_array($singleDigit, array(1, 3, 5, 7, 9))) {
//             return toJSON('', \Constant::GOODS_NO_STOCK);
//         }

        //为了更多人的抢到，抢到的人过24小时才能抢到
        $activitySuccessLog = $this->activityLogService->getLastLog($this->user->id, 1);

        if ($activitySuccessLog != null && $currentAt - $activitySuccessLog->created_at < 86400) {
            //return toJSON('', \Constant::GOODS_NO_STOCK);
        }

        //DB::connection()->enableQueryLog();
        //$affectedRows = Activity::where('activity_id', $activityId)->where('goods_number', '>', 0)->update(['goods_number' => $activity->goods_number - 1]); // 有问题

        $affectedRows = DB::update('UPDATE `mm_activities` SET `remaining_number` = `remaining_number`-1 where `id`=' . $activityId . ' AND `remaining_number` > 0 LIMIT 1');
        //$queries = DB::getQueryLog();

        if ($affectedRows == 0) {
            return toJSON('', \Constant::GOODS_NO_STOCK);
        }

        $activityLog->is_success = 1;
        $activityLog->save();

        $order = $this->orderService->create([
            'user_id' => $this->user->id,
            'sn' => generateOrderSn(),
            'status' => 0,
            'foreign_id' => $activityId,
            'type' => 1,
            'goods_id' => $activity->goods_id,
            'goods_number' => 1
        ]);

        return toJSON($order);
    }

    public function orderConfirm()
    {
        $id     = $this->request->input('id');
        $params = $this->request->input();

        $order = $this->orderService->findFirstRowByFields(['id' => $id, 'user_id' => $this->user->id]);
        if ($order == null) {
            return toJSON('', \Constant::FAILED, '订单不存在');
        }

        if ($order->status != 0) {
            return toJSON('', \Constant::FAILED, '订单已确认，请勿重复提交');
        }

//        if (empty($mobile) || empty($consignee) || empty($province) || empty($city) || empty($district) || empty($address)) {
//            return toJSON('', \Constant::FAILED, '请完善收货信息');
//        }

        $address = json_encode($params);
        //收货地址更新
        $this->user->address = $address;
        $this->user->save();

        $order->status = 1;
        $order->address = $address;
        $order->save();


        return toJSON($this->user);
    }

}
